from orders.models import OrderInfo
from alipay import AliPay
from django.shortcuts import render
from django.conf import settings
from meiduo_mall.utils.constants import Code
from meiduo_mall.utils.login_required import MyLoginRequest
from django import http

from payment.models import PaymentModel


class PaymentView(MyLoginRequest):

    def get(self, request, order_id):
        # 校验参数
        if not all([request, order_id]):
            return http.JsonResponse({'code': Code.PARAMETER_ERROR, 'errmsg': '参数不全'})
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except:
            return http.JsonResponse({'code': Code.PARAMETER_ERROR, 'errmsg': '订单不存在'})
        # 读取公钥，私钥
        with open(settings.ALIPAY_PRIVATE_PATH) as f:
            key_private = f.read()
        with open(settings.ALIPAY_PUBLIC_PATH) as f:
            key_public = f.read()

        # 创建Alipay对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_string=key_private,
            alipay_public_key_string=key_public, sign_type='RSA2',
            debug=settings.ALIPAY_DEBUG
        )
        # 3 获取支付页面
        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城订单",
            return_url=settings.ALIPAY_RETURN_URL,
        )
        alipay_url = settings.ALIPAY_URL + '?' + order_string

        return http.JsonResponse({'code': Code.OK, 'alipay_url': alipay_url})


class PaymentStatusView(MyLoginRequest):
    """
    http://www.meiduo.site:8000/payment/status/?charset=utf-8&
    out_trade_no=20190709180715626693647387971&
    method=alipay.trade.page.pay.return&
    total_amount=3388.00&
    sign=x6gaf6swQq1W7ZiSg%2BfwpcTuxUE9bYRblO6aPKaC6gr7gu32w2EHYc6ZX9PJ8G7RhXWWSeuJ7vcPKxAgz8w6DMRK0KoyIp%2BejDQtd8z%2BvEjuxYTIwA1gd2IAn6QrBIQ2dn%2FmdQeFKEVdSN0cbgLXviWzs4lSiRxCWQm7KMAB81WUXhh1YVtvLDNrWXsuCws9vJ%2FQLz8trIo0Q05dMzCf0cMjVqEu%2FHKuedxFtzWRw28Pj%2FZ0EH6hvfBOu2qdT76Qy0Qswi2kiZOl%2FwI9nhRP2e%2Bhr6CbNCeeNVB8TNjcb1vqxXWK8VcRN1JhME6HE88g9yQ7EyO%2BJByAmNEUHWqqiQ%3D%3D&
    trade_no=2019070922001431031000034303&
    auth_app_id=2016100900647370&
    version=1.0&
    app_id=2016100900647370&
    sign_type=RSA2&
    seller_id=2088102178824247&
    timestamp=2019-07-09+19%3A00%3A40
    """

    def get(self, request):
        data_dict = request.GET.dict()  # 将查询字典转换成真正的字典
        signature = data_dict.pop('sign')  # 使用pop取是因为后面验证的时候不能带有sign
        out_trade_no = data_dict.get('out_trade_no')  # 获取自己生成的订单号
        trade_no = data_dict.get('trade_no')  # 获取支付宝的流水单号

        # 校验数据
        if not all([signature, out_trade_no, trade_no]):
            return http.HttpResponseForbidden('非法请求')

        # 校验整个data数据和sign

        with open(settings.ALIPAY_PRIVATE_PATH) as f:
            key_private = f.read()

        with open(settings.ALIPAY_PUBLIC_PATH) as f:
            key_public = f.read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=key_private,
            alipay_public_key_string=key_public,
            sign_type='RSA2',  # RSA 或RSA2
            debug=settings.ALIPAY_DEBUG
        )
        success = alipay.verify(data_dict, signature)

        if not success:
            return http.JsonResponse('非法请求，数据被篡改')

        # 数据入库
        PaymentModel.objects.create(
            out_trade_no_id=out_trade_no,
            trade_no=trade_no
        )

        OrderInfo.objects.filter(order_id=out_trade_no).update(
            status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']
        )

        return render(request, 'pay_success.html', context={'trade_no': trade_no})
